<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="query.name" placeholder="请输入审批名称" />
      <el-select v-model="query.isOrder" clearable placeholder="请选择是否按顺序审批" filterable>
        <el-option v-for="item in types1" :key="item.id" :label="item.name" :value="item.type" />
      </el-select>
      <el-select v-model="query.whatCheck" clearable style="margin-right:10px;" placeholder="请选择审批对象类型" class="filter-item" filterable>
        <el-option v-for="item in types2" :key="item.id" :label="item.name" :value="item.type" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getInfo">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleAdd('新增审评')">
        {{ $t('table.NewApprovalProcess') }}
      </el-button>
    </div>
    <el-table :data="tableData" row-key="id" highlight-current-row border :header-cell-style="{ 'text-align': 'center' }"
    :cell-style="{ 'text-align': 'center' }">
      <el-table-column prop="name" label="审批名称" />
      <el-table-column prop="createUserName" label="创建人" />
      <el-table-column prop="isOrder" label="是否按顺序审批">
        <template slot-scope="{ row }">
          <span v-if="row.isOrder==1">是</span>
          <span v-if="row.isOrder==2">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="isOrder" label="审批对象类型">
        <template slot-scope="{ row }">
          <span v-if="row.whatCheck==1">审批人</span>
          <span v-if="row.whatCheck==2">审批岗位</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" min-width="190px">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row, $index)">
            {{ $t('table.edit') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="margin-top:20px;" :current-page="query.currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="query.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" :title="dialogType === 'edit' ? '编辑' : text" width="60%">
      <el-form ref="ruleForm" :rules="rules" :model="project" label-width="150px" label-position="left">
        <el-form-item label="审批名称" prop="name">
          <el-input v-model.trim="project.name" style="margin-left: 0;" placeholder="请输入需求名称" maxlength="20" />
        </el-form-item>
        <el-form-item label="是否按顺序审批" prop="isOrder">
          <el-radio v-model="project.isOrder" label="1">是</el-radio>
          <el-radio v-model="project.isOrder" label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="审批对象类型" prop="whatCheck">
          <el-radio-group v-model="project.whatCheck" @change="getdata1">
            <el-radio label="1">指定审批人</el-radio>
            <el-radio label="2">指定审批岗位</el-radio>
          </el-radio-group>
          <span style="margin-left:50px">（注：切换审批类型需要重新创建相应的的功能审批设置）</span>
        </el-form-item>
        <el-form-item v-if="personShow" label="审批对象">
          <el-row>
            <el-select v-if="personShow1" v-model="projectVo.checkName" placeholder="请选择组员" class="filter-item" style="width: 130px" filterable clearable>
              <el-option v-for="item in groupPerson" :key="item.realName" :label="`${item.realName}${item.loginName}`" :value="item.loginName" />
            </el-select>
            <el-select v-if="personShow2" v-model="projectVo.checkName" placeholder="请选择岗位" class="filter-item" style="width: 130px" filterable clearable>
              <el-option v-for="(item,index) in groupStation" :key="index" :label="item.titleName?item.titleName:''" :value="item.titleName?item.titleName:''" />
            </el-select>
            <el-button v-if="personShow1" class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-plus" @click="handleAddMembers">
              {{ $t('table.add') }}
            </el-button>
            <el-button v-if="personShow2" class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-plus" @click="handleAddStation">
              {{ $t('table.add') }}
            </el-button>
          </el-row>
          <el-row>
            <el-table v-if="personShow1" :data="groupPersonList1" style="width: 100% margin-top: 10px" row-key="id" highlight-current-row border>
              <el-table-column key="1" prop="userName" label="组员名" sortable />
              <el-table-column key="6" prop="checkName" label="tel" sortable />
              <el-table-column v-if="project.isOrder==1" key="2" prop="checkOrder" label="审批顺序">
                <template slot-scope="{ row }">
                  <el-input v-model="row.checkOrder" placeholder="请输入审批顺序" maxlength="20" />
                </template>
              </el-table-column>
              <el-table-column key="5" prop="noCheck" label="是否抄送">、
                <template slot-scope="{ row }">
                  <el-radio-group v-model="row.noCheck">
                    <el-radio :label="0">否</el-radio>
                    <el-radio :label="1">是</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column key="3" label="创建时间">
                <template slot-scope="{ row }">
                  <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{m}:{s}') }}</span>
                </template>
              </el-table-column>
              <el-table-column key="4" :label="$t('table.actions')" align="center">
                <template slot-scope="{ row, $index }">
                  <el-button size="mini" type="primary" @click="confirmorder(row, $index,1)">
                    {{ $t('permission.save') }}
                  </el-button>
                  <el-button size="mini" type="danger" @click="handleDeleteGroupPerson(row,$index,1)">
                    {{ $t('table.delete') }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-table v-if="personShow2" :data="groupPersonList2" style="width: 100% margin-top: 10px" row-key="id" highlight-current-row border>
              <el-table-column key="1" prop="checkName" label="岗位名" sortable />
              <el-table-column v-if="project.isOrder==1" key="2" prop="checkOrder" label="审批顺序">
                <template slot-scope="{ row }">
                  <el-input v-model="row.checkOrder" oninput="value=value.replace(/[^\d.]/g,'')" placeholder="请输入审批顺序" maxlength="4" />
                </template>
              </el-table-column>
              <el-table-column key="5" prop="noCheck" label="是否抄送">、
                <template slot-scope="scope">
                  <el-radio-group v-model="scope.row.noCheck">
                    <el-radio :label="0">否</el-radio>
                    <el-radio :label="1">是</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column key="3" label="创建时间">
                <template slot-scope="{ row }">
                  <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{m}:{s}') }}</span>
                </template>
              </el-table-column>
              <el-table-column key="4" :label="$t('table.actions')" align="center">
                <template slot-scope="{ row, $index }">
                  <el-button size="mini" type="primary" @click="confirmorder(row, $index,2)">
                    {{ $t('permission.save') }}
                  </el-button>
                  <el-button size="mini" type="danger" @click="handleDeleteGroupPerson(row,$index,2)">
                    {{ $t('table.delete') }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="canclebtn('canclebtn')">
          {{ $t('permission.close') }}
        </el-button>
        </el-button>
        <el-button type="primary" @click="confirm(1)">
          {{ $t('permission.save') }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" label-width="150px" label-position="left" title="编辑审批顺序" :visible.sync="dialogshow" width="30%">
      <el-form ref="order" :rules="rulesorder" :model="formInline" class="demo-form-inline">
        <el-form-item label="审批顺序" prop="checkOrder">
          <el-input v-model="formInline.checkOrder" style="width:320px;" placeholder="审批顺序" @keyup.native="number" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogshow = false">取 消</el-button>
        <el-button type="primary" @click="confirmorder">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { groupList, getProjectPerson, detail, addchat, getchart, shenHe, download } from '@/api/requireList'
import { getPage, addApprovalProcess, addChecker, getCheckerList, getStationList, getCheckUserPerson, addCheckerStation, delCheckUser, changeorder } from '@/api/approvalProcessSettings'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { deepClone, arraryRemove } from '@/utils'
const project = {
  id: 0,
  name: '',
  isOrder: '',
  status: 1,
  whatCheck: ''
}
const projectVo = {
  checkName: '',
  settingCheckId: '',
  noCheck: 0
}
const formInline = {
  checkOrder: '',
  checkName: ''
}
export default {
  name: 'Project',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      showlie: false,
      dialogshow: false,
      whatCheck: '',
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      listResult: [],
      types2: [
        {
          type: 1,
          name: '指定审批人'
        },
        {
          type: 2,
          name: '指定审批岗位'
        }
      ],
      types1: [
        {
          type: 1,
          name: '是'
        },
        {
          type: 2,
          name: '否'
        }
      ],
      timer: 1,
      group: [],
      material: [],
      projecttype: '',
      rulesorder: {
        checkOrder: [
          { required: true, message: '请填写审批顺序', trigger: 'blur' }
        ]
      },
      rules: {
        name: [
          { required: true, message: '请填写审批名称', trigger: 'blur' }
        ],
        isOrder: [
          { required: true, message: '请选择是否按顺序审批', trigger: 'blur' }
        ],
        whatCheck: [
          { required: true, message: '请选择审批岗位', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      dialogType: 'new',
      total: 0,
      formInline: Object.assign({}, formInline),
      project: Object.assign({}, project),
      projectVo: Object.assign({}, projectVo),
      query: {
        pageIndex: 1,
        pageSize: 10
      },
      personShow1: false,
      personShow2: false,
      personShow: false,
      groupPerson: [],
      groupStation: [],
      tableData: [],
      groupPersonList2: [],
      groupPersonList1: [],
      tableData5: [],
      userList: [],
      show: false,
      chartList: [],
      time: '',
      path: ''
    }
  },
  created() {
    this.getInfo()
  },
  mounted() {
    this.getInfo()
    this.getChecker()
    this.getStation()
  },
  methods: {
    number() {
      this.formInline.checkOrder = this.formInline.checkOrder.replace(/[^\.\d]/g, '')
      this.formInline.checkOrder = this.formInline.checkOrder.replace('.', '')
    },
    confirmorder(row, index, type) {
      if (!row.checkOrder && this.project.isOrder == 1) {
        this.$message({
          type: 'error',
          message: '请填写审批顺序!'
        })
        return false
      }
      if (row.checkOrder == 0 && this.project.isOrder == 1) {
        this.$message({
          type: 'error',
          message: '审批顺序不能为0!'
        })
        return false
      }
      if (index == 0 && row.noCheck == 1) {
        this.$message({
          type: 'error',
          message: '第一个人审批人不能是抄送!'
        })
        return false
      }
      console.log(323232)
      // console.log(type,Number(row.checkOrder),Number(this.groupPersonList1[0].checkOrder),row.noCheck)
      if (type == 1 && Number(row.checkOrder) < Number(this.groupPersonList1[0].checkOrder) && row.noCheck == 1) {
        this.$message({
          type: 'error',
          message: '第一个人审批人不能是抄送!！'
        })
        return false
      }
      if (type == 2 && Number(row.checkOrder) < Number(this.groupPersonList2[0].checkOrder) && row.noCheck == 1) {
        this.$message({
          type: 'error',
          message: '第一个人审批人不能是抄送!！'
        })
        return false
      }
      const obj = {
        settingCheckId: this.project.id,
        checkName: row.checkName,
        checkOrder: row.checkOrder,
        noCheck: row.noCheck
      }
      changeorder(obj).then((res) => {
        if (res.isSuccess) {
          this.dialogshow = false
          this.getCheckUser(this.project.id)
          this.$message({
            type: 'success',
            message: '保存成功'
          })
        } else {
          this.$message({
            type: 'warning',
            message: res.message
          })
        }
      })
    },
    editOrder(row) {
      this.dialogshow = true
      this.formInline = deepClone(row)
    },
    getCheckUser(id) {
      getCheckUserPerson(id).then((res) => {
        if (this.project.whatCheck == 1) {
          this.groupPersonList1 = res.data.items
          this.groupPersonList2 = []
        } else if (this.project.whatCheck == 2) {
          this.groupPersonList2 = res.data.items
          this.groupPersonList1 = []
        } else {
          this.groupPersonList1 = []
          this.groupPersonList2 = []
        }
      })
    },
    getdata1(e) {
      this.personShow = true
      if (e == '1') {
        this.personShow1 = true
        this.personShow2 = false
      } else {
        this.personShow2 = true
        this.personShow1 = false
      }
    },
    getdata(e) {
      this.personShow = true
      if (e == 1) {
        this.personShow1 = true
        this.personShow2 = false
      } else {
        this.personShow2 = true
        this.personShow1 = false
      }
      this.getCheckUser(this.project.id)
    },
    async getChecker() {
      this.groupPerson = await getCheckerList()
    },
    getStation: function() {
      getStationList().then((res) => {
        this.groupStation = res.data
      })
    },
    async handleDeleteGroupPerson(row, index, type) {
      if (type == 1 && index == 0) {
        for (var i = 0; i < this.groupPersonList1.length; i++) {
          if (this.groupPersonList1[i].noCheck == 1) {
            this.$message({
              type: 'error',
              message: '审批流存在抄送人，不能删除第一条'
            })
            return false
          }
        }
      } else if (type == 2 && index == 0) {
        for (var i = 0; i < this.groupPersonList2.length; i++) {
          if (this.groupPersonList2[i].noCheck == 1) {
            this.$message({
              type: 'error',
              message: '审批流存在抄送人，不能删除第一条'
            })
            return false
          }
        }
      }
      this.$confirm('确认删除?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await delCheckUser(row.id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getCheckUser(this.project.id)
        })
        .catch((err) => console.error(err))
    },
    handleSizeChange(size) {
      this.query.pageSize = size
    },
    handleCurrentChange(currentPage) {
      this.query.currentPage = currentPage
    },
    canclebtn(ruleForm) {
      this.dialogVisible = false
    },
    async getInfo() {
      const {data,total} = await getPage(this.query)
      this.tableData = data;
      this.total = total
    },
    search() {
      this.query.pageIndex = 1
      this.getInfo()
    },
    handleAdd(text) {
      this.dialogVisible = true
      this.show = false
      this.text = text
      this.project = Object.assign({}, project)
      this.dialogType = 'new'
      this.groupPersonList1 = []
      this.groupPersonList2 = []
      this.personShow = false
      this.personShow1 = true
      this.personShow2 = false
    },
    handleUpdate(row, $index) {
      this.dialogType = 'edit'
      this.text = '编辑需求'
      this.dialogVisible = true
      this.projectVo = Object.assign({}, projectVo)
      this.project = deepClone(row)
      this.whatCheck = this.project.whatCheck + ''
      this.project.whatCheck = this.project.whatCheck + ''
      this.project.isOrder = this.project.isOrder + ''
      this.getdata(this.project.whatCheck)
      this.getChecker()
      this.getStation()
    },
    async confirm(type) {
      const obj = this.project
      const isEdit = this.dialogType === 'edit'
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          addApprovalProcess(obj).then(res => {
            if (res.isSuccess) {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.getInfo()
              this.dialogVisible = false
            }
          })
        }
      })
    },
    async handleAddMembers() {
      if (this.project.id > 0) {
        if (this.whatCheck === this.project.whatCheck) {
          this.projectVo.settingCheckId = this.project.id
          if (this.projectVo.checkName) {
            addChecker(this.projectVo).then((res) => {
              if (!res.isSuccess) {
                this.$notify({
                  title: '提示',
                  dangerouslyUseHTMLString: true,
                  message: res.message,
                  type: 'error'
                })
              } else {
                this.getCheckUser(this.project.id)
                this.$notify({
                  title: '提示',
                  dangerouslyUseHTMLString: true,
                  message: '添加成功',
                  type: 'success'
                })
              }
            })
          } else {
            this.$notify({
              title: '提示',
              dangerouslyUseHTMLString: true,
              message: `请选择审批对象`,
              type: 'warning'
            })
          }
        } else {
          this.$notify({
            title: '提示',
            dangerouslyUseHTMLString: true,
            message: `修改审批对象类型后请先保存编辑,再添加审批对象`,
            type: 'warning'
          })
        }
      } else {
        this.$notify({
          title: '提示',
          dangerouslyUseHTMLString: true,
          message: `请先保存审批，然后编辑添加审批人员`,
          type: 'warning'
        })
      }
    },
    async handleAddStation() {
      if (this.project.id > 0) {
        if (this.whatCheck === this.project.whatCheck) {
          this.projectVo.settingCheckId = this.project.id
          if (this.projectVo.checkName) {
            addCheckerStation(this.projectVo).then((res) => {
              if (!res.isSuccess) {
                this.$notify({
                  title: '提示',
                  dangerouslyUseHTMLString: true,
                  message: res.message,
                  type: 'error'
                })
              } else {
                this.getCheckUser(this.project.id)
                this.$notify({
                  title: '提示',
                  dangerouslyUseHTMLString: true,
                  message: '添加成功',
                  type: 'success'
                })
              }
            })
          } else {
            this.$notify({
              title: '提示',
              dangerouslyUseHTMLString: true,
              message: `请选择审批对象`,
              type: 'warning'
            })
          }
        } else {
          this.$notify({
            title: '提示',
            dangerouslyUseHTMLString: true,
            message: `修改审批对象类型后请先保存编辑,再添加审批对象`,
            type: 'warning'
          })
        }
      } else {
        this.$notify({
          title: '提示',
          dangerouslyUseHTMLString: true,
          message: `请先保存审批，然后编辑添加审批人员`,
          type: 'warning'
        })
      }
    }
  }
}
</script>
<style scoped>
.item {
  padding-top: 10px;
  margin-top: 50px;
  border-radius: 10px;
}
.outinner {
  display: flex;
  align-items: flex-end;
}
.out {
  margin-top: 20px;
  width: 100%;
  bottom: 20px;
}
.itemInner {
  padding: 20px;
}
.name {
  margin-bottom: 10px;
  color: #9999
}
.time {
  color: #9999
}
.txt {
  width: 90%;
}
input {
  margin: 0;
}
.el-picker-panel__footer .el-button--text.el-picker-panel__link-btn {
  display: none;
}
.ban {
  text-align: left;
  font-weight: bold;
  font-size: 20px;
  background: #7ba4e17a;
  padding: 10px;
  border-radius: 10px;
  color: #fff;
}
</style>
